package cn.micai.base.asyn;

import java.util.concurrent.*;

/**
 * 描述：Java5， Callable, Future, FutureTask
 * <p>
 *   通过Runable和Thread， 无法获取子线程的运行结果。
     Java5 引入了java.util.concurrent， 可以获取到子线程的运行结果。
     Future接口可以理解成一个任务， Future.get()方法可以获取任务的运行结果

     例子步骤：

     1）创建一个RMTask和CUPDTask， 实现Callable接口。 重写call（）方法去实现任务

     2）通过Executors类去创建一个线程池

     3）通过Executors.submit()去创建子线程去执行任务。
 *
 * @author: 赵新国
 * @date: 2018/5/25 15:42
 */
public class J5Thread {

    public static void main(String [] args) {
        // executorService
        System.out.println("Get request from TC, thread id="+Thread.currentThread().getId());
        ExecutorService executorService = Executors.newCachedThreadPool();

        // task
        Callable<Integer> rmTask = new RMTask();
        Callable<Integer> cupdTask = new CUPDTask();

        //ES submit task,
        //param is callable
        //return result
        Future<Integer> rmResult = executorService.submit(rmTask);
        Future<Integer> cupdResult = executorService.submit(cupdTask);
        executorService.shutdown();

        System.out.println("ES shutdown, thread id="+Thread.currentThread().getId());
        //ES shutdown

        try {
            Integer result = rmResult.get();
            System.out.println("process rmResult, thread id="+Thread.currentThread().getId());
            System.out.println("process rmResult="+result);
            Integer cupdresult = cupdResult.get();
            System.out.println("process cupdResult, thread id="+Thread.currentThread().getId());
            System.out.println("process cupdResult="+cupdresult);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    // define task
    static class RMTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("creating response Rich media, thread id="+Thread.currentThread().getId());
            Thread.sleep(3000);
            System.out.println("end response Rich media, thread id="+Thread.currentThread().getId());
            return new Integer(3);
        }
    }

    static class CUPDTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("creating CUPD msg, thread id="+Thread.currentThread().getId());
            Thread.sleep(8000);
            System.out.println("end response Rich media, thread id="+Thread.currentThread().getId());
            return new Integer(10);
        }
    }

}
